package org.example.zuoye.controller;


import jakarta.servlet.http.HttpSession;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.example.zuoye.common.ClientLoginInterceptor;
import org.example.zuoye.entity.Patient;
import org.example.zuoye.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/client")
@Slf4j
public class LoginController {
    // public static final PasswordEncryptor pe = new StrongPasswordEncryptor();
    private PatientService patientService;

    @Autowired
    public void setPatientService(PatientService patientService) {
        this.patientService = patientService;
    }

    @GetMapping("/login")
    public String login() {
        return "client/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(Patient account, HttpSession session) {
        Patient patient = this.patientService.findByPhone(account.getPhone());
        if (ObjectUtils.isEmpty(patient)) {
            return Map.of("success", false, "error", "用户不存在");
        }

        // if (pe.checkPassword(account.getPassword(), patient.getPassword())) {
        if (patient.getPassword().equals(account.getPassword())) {
            session.setAttribute(ClientLoginInterceptor.CLIENT_USER_KEY, patient);

            return Map.of("success", true, "data", patient);
        } else {
            return Map.of("success", false, "error", "密码不正确");
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(ClientLoginInterceptor.CLIENT_USER_KEY);
        log.info("logout");
        return "/client/login";
    }
}
